package com.example.swimfish;

import java.net.DatagramPacket;
import java.net.DatagramSocket;


//响应UDP广播
public class PeerDiscoveryServer {
    public static final int DISCOVERY_PORT = 8888;
    public static final String DISCOVERY_MESSAGE = "DISCOVER_SWIMFISH_PEER";
    private volatile boolean running = true;

    public void start() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(DISCOVERY_PORT)) {
                socket.setBroadcast(true);

                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                while (running) {
                    socket.receive(packet);
                    String received = new String(packet.getData(), 0, packet.getLength());

                    if (DISCOVERY_MESSAGE.equals(received.trim())) {
                        // 收到发现请求，发送响应
                        byte[] response = NetworkUtils.getLocalIP().getBytes();
                        DatagramPacket responsePacket = new DatagramPacket(
                                response,
                                response.length,
                                packet.getAddress(),
                                packet.getPort()
                        );
                        socket.send(responsePacket);
                    }
                }
            } catch (Exception e) {
                if (running) { // 忽略正常停止时的异常
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void stop() {
        running = false;
    }
}